package com.tiancheng.onecode.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: kellen
 * @Description: sha工具类
 * @Date: create in 2024/12/10 11:07
 */
public class ShaUtils {
    public static final String KEY_SHA = "SHA";
    public static final String ra = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    /**
     * 字符串sha加密
     *
     * @param s 要加密的字符串
     * @return 加密后的字符串
     */
    public static String sha(String s) {
        BigInteger sha = null;
        byte[] bys = s.getBytes();
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(KEY_SHA);
            messageDigest.update(bys);
            sha = new BigInteger(messageDigest.digest());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sha.toString(32);
    }

    /**
     * 字符串+随机盐 sha加密
     *
     * @param pwd  要加密的字符串
     * @param salt 盐
     * @return 盐和加密后的字符串
     */
    public static String encryption(String pwd, String salt) {
        return sha(pwd + salt);
    }

    /**
     * 生成随机盐
     *
     * @return 随机生成的盐
     */
    public static String getSalt() {
        SecureRandom random = new SecureRandom();
        int length = random.nextInt(5) + 8;//盐的长度，这里是8-12可自行调整
        char[] text = new char[length];
        for (int i = 0; i < length; i++) {
            text[i] = ra.charAt(random.nextInt(ra.length()));
        }
        return new String(text);
    }
}
